import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';

class BlockRefreshWithScopedModel extends StatefulWidget {
  const BlockRefreshWithScopedModel({Key? key}) : super(key: key);

  @override
  _BlockRefreshWithScopedModelState createState() =>
      _BlockRefreshWithScopedModelState();
}

class _BlockRefreshWithScopedModelState
    extends State<BlockRefreshWithScopedModel> {
  int currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return ScopedModel(
        model: PositionModel(),
        child: Scaffold(
          appBar: AppBar(
            title: Text("Scoped Model局部刷新"),
            centerTitle: true,
          ),
          body: Container(
            child: Row(
              children: [
                Container(
                  color: Colors.grey[100],
                  width: 100,
                  child: LeftMenuWidget(),
                ),
                Expanded(child: RightMenu())
              ],
            ),
          ),
        ));
  }
}

class PositionModel extends Model {
  int currentIndex = 0;

  void changePageIndex(int newIndex) {
    currentIndex = newIndex;
    notifyListeners();
  }
}

class LeftMenuWidget extends StatefulWidget {
  const LeftMenuWidget({Key? key}) : super(key: key);

  @override
  _LeftMenuWidgetState createState() => _LeftMenuWidgetState();
}

class _LeftMenuWidgetState extends State<LeftMenuWidget> {
  List<String> list = ["菜单1", "菜单2", "菜单3"];

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<PositionModel>(
      builder: (context, _, model) {
        return Container(
          child: ListView.separated(
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(
                    list[index],
                    style: Theme.of(context).textTheme.bodyText1,
                  ),
                  onTap: () {
                    model.changePageIndex(index);
                  },
                );
              },
              separatorBuilder: (context, index) {
                return Divider();
              },
              itemCount: list.length),
        );
      },
    );
  }
}

class RightMenu extends StatefulWidget {
  const RightMenu({Key? key}) : super(key: key);

  @override
  _RightMenuState createState() => _RightMenuState();
}

class _RightMenuState extends State<RightMenu> {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<PositionModel>(builder: (context, _, model) {
      return Container(
        child: Center(
          child: Text("${model.currentIndex}"),
        ),
      );
    });
  }
}
